package net;

import java.io.IOException;
import java.net.InetAddress;

/**
 * ip地址演示
 * @author fidel
 */
public class InetAddressDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        InetAddress address = (InetAddress) InetAddress.getLocalHost();
        // 返回主机地址
        System.out.println(address.getHostAddress());
        // 返回主机名
        System.out.println(address.getHostName());
        address = InetAddress.getByName("java.com");
        System.out.println(address.getHostAddress());
        System.out.println(address);
        int timeout = 3000;
        String hostName = address.getHostName();
        for (int i = 0; i < 4; i++) {
            // 测试该地址是否在指定时间内是否可以到达（单位：毫秒）
            synchronized (address) {
                if (address.isReachable(timeout)) {
                    System.out.println("在" + timeout + "毫秒超时值内成功访问目标主机" + hostName);
                } else {
                    System.out.println("访问目标主机" + hostName + "超时");
                }
                address.wait(1000);
            }
        }
    }
}
